package com.activemqwrap.tools.tcpforward;

import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

public class WatchDog {

    public int watchIntervalTime = 10 * 1000;
    public int printInfoIntervalTime = 3 * 1000;
//    public int killThreshold = 15 * 60 * 1000;//60秒

    //    public int watchIntervalTime;
//    public int printInfoIntervalTime;
    public int killThreshold;

    private ProxyMQ proxyMQ;
    private boolean dogRushFlag = false;

    public WatchDog(ProxyMQ proxymq) {
        proxyMQ = proxymq;
    }

    public void runDog() {
        dogRushFlag = true;

        new Thread(() -> {
            while (dogRushFlag) {
                try {
                    //check inSockets
                    for (String key : proxyMQ.inSockets.keySet()) {
                        SocketExt se = proxyMQ.inSockets.get(key);
                        if (StringUtils.isEmpty(se.socket)
                                || se.socket.isClosed()
                                || new Date().getTime() - se.lastCommTime.getTime() > killThreshold) {
                            kill_Both_Socket(key);
                        }

                    }
                    //check outSockets
                    for (String key : proxyMQ.outSockets.keySet()) {
                        SocketExt se = proxyMQ.outSockets.get(key);
                        if (StringUtils.isEmpty(se.socket)
                                || se.socket.isClosed()
                                || new Date().getTime() - se.lastCommTime.getTime() > killThreshold) {
                            kill_Both_Socket(key);
                        }
                    }
                    Thread.sleep(watchIntervalTime);

                } catch (Exception e) {
                    System.out.println("---watchDog---error:watchInterval---" + e.getMessage());
                }

            }

        }).start();

        //print socketInfo
        new Thread(() -> {
            while (dogRushFlag) {
                try {
                    Thread.sleep(printInfoIntervalTime);
                    int count_inSockets = proxyMQ.inSockets.size();
                    int count_outSockets = proxyMQ.outSockets.size();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    String strDate = df.format(new Date());
                    System.out.println(strDate + "---watchDog---当前接入socket数：" + count_inSockets);
                    System.out.println(strDate + "---watchDog---当前转发socket数：" + count_outSockets);
                } catch (Exception e) {
                    System.out.println("---watchDog---error:print Socket Info---" + e.getMessage());
                }
            }

        }).start();

    }

    public void stopDog() {
        dogRushFlag = false;
    }

    public void kill_Both_Socket(String socketName) {
        try {
            System.out.println(System.currentTimeMillis() + "---watchDog---in_socket  will be kill-" + socketName);
            SocketExt inSockets = proxyMQ.inSockets.get(socketName);
            inSockets.socket.shutdownInput();
            inSockets.socket.shutdownOutput();
            inSockets.socket.close();
            //删除返回数datatable据表
            removeReturnData(socketName, proxyMQ.returnDataTable);

        } catch (Exception e) {
            System.out.println("---watchDog---error:killinSockets---" + e.getMessage());
        } finally {
            //移除socket记录表
            proxyMQ.inSockets.remove(socketName);
        }

        try {
            System.out.println(System.currentTimeMillis() + "---watchDog---out_socket will be kill-" + socketName);
            SocketExt outSockets = proxyMQ.outSockets.get(socketName);
            outSockets.socket.shutdownInput();
            outSockets.socket.shutdownOutput();
            outSockets.socket.close();

        } catch (Exception e) {
            System.out.println("---watchDog---error:killoutSockets---" + e.getMessage());
        } finally {
            //移除socket记录表
            proxyMQ.outSockets.remove(socketName);
        }

    }

    public void removeReturnData(String key, Hashtable<String, String> returnDataTable) {
        try {
            System.out.println(System.currentTimeMillis() + "watchDog---ReturnData will be kill -" + key);
            returnDataTable.remove(key);
        } catch (Exception e) {
            System.out.println("---watchDog---error:removeReturnData---" + e.getMessage());
        }

    }

}
